package itbour.onetouchshow.activity.video.make;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.OneToucDialog;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.andview.adapter.ABaseRefreshAdapter;
import com.andview.adapter.BaseRecyclerHolder;
import com.andview.form.FormElement;
import com.andview.form.OnFormElementValueChangedListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lsjr.utils.NetUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import itbour.onetouchshow.R;
import itbour.onetouchshow.activity.version1_2.CutVideoActivity;
import itbour.onetouchshow.activity.version1_4.V1_4_VideoPreviewActivity;
import itbour.onetouchshow.activity.video.videoplay.VideoPlayPreviewActivity;
import itbour.onetouchshow.adapter.VideoEditAdapter;
import itbour.onetouchshow.base.SPCTag;
import itbour.onetouchshow.base.mvp.MVPBaseActivity;
import itbour.onetouchshow.bean.ClipVideoBean;
import itbour.onetouchshow.bean.VideoMoule;
import itbour.onetouchshow.bean.VideoPreviewBean;
import itbour.onetouchshow.bean.canvas.CompoundPathsBean;
import itbour.onetouchshow.bean.canvas.PosBean;
import itbour.onetouchshow.bean.eventbus.UpdateUserAction;
import itbour.onetouchshow.bean.inching.DocContentV10Bean;
import itbour.onetouchshow.bean.inching.noppt.InchingCoreRootNoPPTV10Bean;
import itbour.onetouchshow.bean.inching.noppt.InchingDocStringNoPPTV10Bean;
import itbour.onetouchshow.bean.inching.noppt.NoPPTRootTextValueV10Bean;
import itbour.onetouchshow.bean.user.UserMakeTag;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.constants.platform.WorkPlatform;
import itbour.onetouchshow.listener.SoftKeyBoardListener;
import itbour.onetouchshow.utils.AppCommNetUtils;
import itbour.onetouchshow.utils.BroadcastAction;
import itbour.onetouchshow.utils.CommonUtils;
import itbour.onetouchshow.utils.FinshBroadcast;
import itbour.onetouchshow.utils.ImageLoader;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.OnMultiClickUtils;
import itbour.onetouchshow.utils.SpUtils;
import itbour.onetouchshow.utils.T_;
import itbour.onetouchshow.utils.UIUtils;
import itbour.onetouchshow.utils.gsonanalysis.CoreObjToJsonNoPPTRules;
import itbour.onetouchshow.utils.gsonanalysis.DocStringJsonToObjCommonRules;
import itbour.onetouchshow.utils.gsonanalysis.RootTextValueV10RemoveToJsonRules;
import itbour.onetouchshow.utils.video.MakeProductContrl;
import itbour.onetouchshow.widget.BoundView;
import recycler.coverflow.CoverFlowLayoutManger;
import recycler.coverflow.RecyclerCoverFlow;

import static itbour.onetouchshow.bean.eventbus.UpdateUserAction.TYPE_CREATEWORK;


/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */
@SuppressLint("ValidFragment")
public class MakeActivity extends MVPBaseActivity<MakeContract.View, MakePresenter> implements MakeContract.View {

    public InchingDocStringNoPPTV10Bean noPptCoreData;
    @BindView(R.id.id_rv_viewpager)
    protected RecyclerCoverFlow idRvViewpager;
    @BindView(R.id.id_rv_data)
    protected RecyclerView idRvData;
    @BindView(R.id.ll_bootm_View)
    protected LinearLayout llBootmView;
    @BindView(R.id.rl_root)
    protected RelativeLayout llRoot;
    @BindView(R.id.tv_page_tag)
    protected TextView tvPageTag;
    protected Map<Integer, List<InchingCoreRootNoPPTV10Bean>> wantData;
    protected ViewPagerAdapter viewPagerAdapter;
    protected int viewpagerTopmargen;
    protected int MAKE_WORK_STATE = MakeProductContrl.MAKE_COMPLETED;
    protected List<String> thumbs = new ArrayList<>();
    @BindView(R.id.id_tv_make_show)
    TextView idTvMakeShow;
    @BindView(R.id.id_tv_make_over)
    TextView idTvMakeOver;
    VideoMoule videoModuleBean;
    /*用户操作类型*/
    UserMakeTag state = UserMakeTag.MAKE;
    String module;
    OneToucDialog oneToucDialog;
    private VideoEditAdapter videoEditAdapter;
    private String type;
    //记录的docString
    private String currentDocString;
    private String makeDocString;
    private OnFormElementValueChangedListener valueChangedListener = new OnFormElementValueChangedListener() {
        @Override
        public void onValueChanged(FormElement formElement) {
            L_.e("onValueChanged: " + formElement.getTitle() + "修改成为" + formElement.getValue());
        }
    };
    //这是用于退出三段式逻辑的广播
    private FinshBroadcast quitThreeLogicBroadcast = new FinshBroadcast();

    public UserMakeTag getState() {
        return state;
    }

    public void setState(UserMakeTag state) {
        this.state = state;
    }

    @Override
    public void loadSucceed(String result) {

    }

    @Override
    public void loadFaild(String error) {
        dismissProgressDialog();
    }

    @Override
    protected void initTitle() {
        super.initTitle();
        registerExitReceiver();
        setTitleText("视频制作");
        getToolBarView().setRightText("存草稿");
        getToolBarView().getRightTextView().setVisibility(View.VISIBLE);
        getToolBarView().getRightTextView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setState(UserMakeTag.SAVE);
                makeVideoPreview();

            }
        });
        getToolBarView().getLeftimageView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                jugleQuit();
            }
        });
        initKeyBroadListener();

    }

    public void jugleQuit() {
        makeDocString = new GsonBuilder()
                .registerTypeAdapter(InchingCoreRootNoPPTV10Bean.class, new CoreObjToJsonNoPPTRules())
                .registerTypeAdapter(NoPPTRootTextValueV10Bean.class, new RootTextValueV10RemoveToJsonRules())
                .create().toJson(noPptCoreData);
        L_.e(makeDocString);
        L_.e(currentDocString);

        if (getState().equals(UserMakeTag.SAVE)) {
            EventBus.getDefault().post(1800);
        }
        if (makeDocString.equals(currentDocString)) {
            finish();
        } else {
            showDialog();
        }


    }

    @Override
    public void finish() {
//        if (mPresenter.makeProductContrl != null && mPresenter.makeProductContrl.oneToucDialog != null)
//            if (mPresenter.makeProductContrl.oneToucDialog.isShowing()) {
//                mPresenter.makeProductContrl.oneToucDialog.dismiss();
//            }
//        if (mPresenter.makeProductContrl != null) {
//            mPresenter.makeProductContrl = null;
//        }
        super.finish();
        L_.e("makle  _finish");
    }

    public void showDialog() {
        new OneToucDialog.Builder(this)
                .content("是否保存本次编辑并退出")
                .positiveText("确定").onPositive(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                Log.e("TAH", "点击确定");
                // complexDialogFrag.dismiss();
                setState(UserMakeTag.CLOSE);
                makeVideoPreview();
            }
        })
                .negativeText("取消").onNegative(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                Log.e("TAH", "点击确定");
                finish();
            }
        }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE)
                .cancelable(false)
                .show();


    }

    @Override
    public void onBackPressed() {
        jugleQuit();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_make_video;
    }

    protected void initKeyBroadListener() {
        SoftKeyBoardListener.setListener(MakeActivity.this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                L_.i("键盘显示 高度" + height);
                int saveHeight = SpUtils.getInt(SPCTag.KEYBROAD_HEIGHT, 0);
                if (saveHeight == 0 || saveHeight < 300) {
                    SpUtils.putInt(SPCTag.KEYBROAD_HEIGHT, height);
                }

                if (llBootmView != null) {
                    llBootmView.setVisibility(View.GONE);
                }
            }

            @Override
            public void keyBoardHide(int height) {
                L_.i("键盘隐藏 高度" + height);
                // videoEditAdapter.getEditTextView().clearFocus();
                if (llBootmView != null) {
                    llBootmView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (llBootmView != null) {
                                llBootmView.setVisibility(View.VISIBLE);
                            }
                        }
                    }, 200);
                }
            }
        });
    }

    @Override
    protected void afterCreate(Bundle savedInstanceState) {
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            module = extras.getString("module");
            type = extras.getString(WorkPlatform.TYPE);
            MAKE_WORK_STATE = extras.getInt(AppConst.MAKE_WORK_STATE);
        }
        mPresenter = new MakePresenter(this, this);
        mPresenter.setMakeActivity(this);
        videoModuleBean = new Gson().fromJson(module, VideoMoule.class);
    }

    @Override
    protected void initData() {
        super.initData();


        if (TextUtils.isEmpty(module)) return;

        L_.i(module);
        DocContentV10Bean docContentV10Bean = new GsonBuilder().registerTypeAdapter(DocContentV10Bean.class, new DocStringJsonToObjCommonRules())
                .create().fromJson(module, DocContentV10Bean.class);
        noPptCoreData = docContentV10Bean.getNoPptCoreData();

        //如果本地支持版本小于服务器版本   不让用户操作   提醒升级
        if (AppConst.SUPPROT_VIDEO_VERSION < noPptCoreData.getCoreStructure().getVersion()) {
            //TODO  提醒用户升级
            AppCommNetUtils.showUpgrade(MakeActivity.this);
            return;
        }

        //得到当前数据保存和后面用户数据做比较
        String curdocString = getMakeDocString();
        currentDocString = curdocString;
        makeDocString = curdocString;

        // InchingDocStringNoPPTV10Bean.CoreStructureBean coreStructure = noPptCoreData.getCoreStructure();
        wantData = mPresenter.getWantData(noPptCoreData);

        initViewPager();
        initRvEditVideo();

    }

    protected void initRvEditVideo() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MakeActivity.this, LinearLayoutManager.VERTICAL, false);
        videoEditAdapter = new VideoEditAdapter(MakeActivity.this, wantData);
        videoEditAdapter.setOnPictureIvClickListener(new VideoEditAdapter.OnPictureIvClickListener() {
            @Override
            public void getPictureIv() {
                //去裁界面
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, AppConst.TOPHOTO);
            }

            @Override
            public void addBoundView(InchingCoreRootNoPPTV10Bean data) {
                if (noPptCoreData == null) {
                    return;
                }
                getAndroiodScreenProperty();


                int[] locationMove = new int[2];
                idRvViewpager.getLocationOnScreen(locationMove);//获取在整个屏幕内的绝对坐标
                int viewInWindowsX = locationMove[0];
                int viewInWindowsY = locationMove[1];


                //确定当前选中的位置
                int centerWidth = UIUtils.WHD()[0] / 4 + UIUtils.WHD()[0] / 2;
                int centerHeight = (int) (centerWidth * 1.0f * 9.0f / 16.0f);

                int pageWidth = noPptCoreData.getPageWidth();
                int pageHeight = noPptCoreData.getPageHeight();

                float scaleW = centerWidth * 1.0f / pageWidth;
                float scaleH = centerHeight * 1.0f / pageHeight;

                CompoundPathsBean bound = data.getRelations().get(0).getBound();
                PosBean pos = data.getRelations().get(0).getPos();
                float w = bound.getW() * scaleW;
                float h = bound.getH() * scaleH;
                float x = pos.getX() * scaleW;
                float y = pos.getY() * scaleH;
                BoundView pathsView = new BoundView(MakeActivity.this);
                pathsView.setId(R.id.video_edit_bound);
                pathsView.setData(bound, (int) w, (int) h);

                RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams((int) w, (int) h);
                // lp.leftMargin = (int) x + (UIUtils.WHD()[0] - (UIUtils.WHD()[0] / 4 + UIUtils.WHD()[0] / 2)) / 2;
                // lp.topMargin = (int) y + viewpagerTopmargen;
                lp.leftMargin = (int) x;
                lp.topMargin = (int) y;
                // L_.e("addBoundView===" + lp.leftMargin + "centerHeight===" + lp.topMargin);
                llRoot.addView(pathsView, lp);
                // CommonUtils.flashAnimontion(pathsView);
                L_.i("addBoundView===" + centerWidth + "centerHeight===" + centerHeight);
            }

            @Override
            public void removeBoundView() {
                if (llRoot != null) {
                    for (int i = 0; i < llRoot.getChildCount(); i++) {
                        View viewById = llRoot.findViewById(R.id.video_edit_bound);
                        if (viewById != null) {
                            viewById.clearAnimation();
                            llRoot.removeView(viewById);
                            // llRoot.removeAllViews();
                        }
                    }
                }
            }

            @Override
            public void getCurrentPic(int position, String url) {
                idRvViewpager.scrollToPosition(position);
                if (url == null) {
                    thumbs.set(idRvViewpager.getSelectedPos(), noPptCoreData.getSceneThumbs().get(position));
                } else {
                    thumbs.set(idRvViewpager.getSelectedPos(), url);
                }

                tvPageTag.setText((position + 1) + "/" + wantData.size());
                // thumbs.get()
                viewPagerAdapter.notifyDataSetChanged(thumbs);

            }
        });
        //videoEditAdapter.add
        idRvData.addOnScrollListener(new MyRecyclerViewScrollListener());
        idRvData.setLayoutManager(linearLayoutManager);
        idRvData.setAdapter(videoEditAdapter);
    }

    public void getAndroiodScreenProperty() {
        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;         // 屏幕宽度（像素）
        int height = dm.heightPixels;       // 屏幕高度（像素）
        float density = dm.density;         // 屏幕密度（0.75 / 1.0 / 1.5）
        int densityDpi = dm.densityDpi;     // 屏幕密度dpi（120 / 160 / 240）
        // 屏幕宽度算法:屏幕宽度（像素）/屏幕密度
        int screenWidth = (int) (width / density);  // 屏幕宽度(dp)
        int screenHeight = (int) (height / density);// 屏幕高度(dp)

    }

    protected void initViewPager() {
        tvPageTag.setText("1" + "/" + wantData.size());
        thumbs.addAll(noPptCoreData.getSceneThumbs());
        if (thumbs != null && thumbs.size() > 0) {
            //L_.e(thumbs.size() + ":" + thumbs.get(0));
            viewPagerAdapter = new ViewPagerAdapter(getApplication(), thumbs, R.layout.item_make_adapter);
            idRvViewpager.setAdapter(viewPagerAdapter);
            idRvViewpager.addOnScrollListener(new ViewPagerRecyclerViewScrollListener());
        }

        RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) llRoot.getLayoutParams();
        layoutParams1.width = UIUtils.WHD()[0] / 4 + UIUtils.WHD()[0] / 2;
        layoutParams1.height = (int) (layoutParams1.width * 1.0f * 9.0f / 16.0f);

        if (thumbs.size() > 1) {
            tvPageTag.setVisibility(View.VISIBLE);
        } else {
            tvPageTag.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initView() {
        super.initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("p3-视频模板制作页"); //统计页面(仅有Activity的应用中SDK自动调用，不需要单独写。"SplashScreen"为页面名称，可自定义)
        MobclickAgent.onResume(this);
//        if (oneTouchProgressDialog != null) {
//            oneTouchProgressDialog.dismiss();
//        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("p3-视频模板制作页"); // （仅有Activity的应用中SDK自动调用，不需要单独写）保证 onPageEnd 在onPause 之前调用,因为 onPause 中会保存信息。"SplashScreen"为页面名称，可自定义
        MobclickAgent.onPause(this);
    }

    @OnClick({R.id.id_tv_make_show, R.id.id_tv_make_over})
    public void onViewClicked(View view) {
        if (OnMultiClickUtils.isFastClick()) {
            if (NetUtils.isConnected(getApplication())) {
                switch (view.getId()) {
                    case R.id.id_tv_make_show:
                        //mPresenter.loadDocPreview(videoModuleBean.getDocId() + "");
                        setState(UserMakeTag.SHOW);
                        makeVideoPreview();
                        break;
                    case R.id.id_tv_make_over:
                        setState(UserMakeTag.MAKE);
                        makeVideoPreview();
                        break;
                    default:
                        break;
                }
            } else {
                T_.showCustomToast("请检查网络");
            }
        }

    }

    public void makeVideoPreview() {

        makeDocString = getMakeDocString();
        L_.e(makeDocString);

        if (TextUtils.isEmpty(mPresenter.getDocId())) {
            if (type.equals(WorkPlatform.MOUDLE)) {
                mPresenter.loadMakeVideo(videoModuleBean.getTmplId() + "", makeDocString);
            } else {
                mPresenter.upDataMakeVideo(videoModuleBean.getDocId() + "", makeDocString);
            }
        } else {
            //没有修改直接调用预览
            if (makeDocString.equals(currentDocString)) {
                if (getState().equals(UserMakeTag.SAVE)) {
                    T_.showCustomToast("存草稿成功");
                    dismissProgressDialog();
                    return;
                }
                /**
                 * 如果是生成失败过的
                 *
                 * 则先调用更新接口
                 *
                 */
                if (MAKE_WORK_STATE == MakeProductContrl.MAKE_FAILE) {
                    mPresenter.upDataMakeVideo(mPresenter.getDocId() + "", makeDocString);
                } else {
                    mPresenter.loadDocPreview(mPresenter.getDocId());
                }
            } else {
                mPresenter.upDataMakeVideo(mPresenter.getDocId() + "", makeDocString);
            }
        }
        currentDocString = makeDocString;
    }

    public void showNewDialog() {
        OneToucDialog.Builder builder = new OneToucDialog.Builder(this);
        int width = UIUtils.WHD()[0] / 3;
        int height = UIUtils.WHD()[0] / 4;
        if (getState().equals(UserMakeTag.SHOW)) {
            // oneTouchProgressDialog.setTitle("正在生成预览");
            builder.content("正在生成预览");
        } else {
            // oneTouchProgressDialog.setTitle("正在生成作品");
            builder.content("正在生成作品");
        }
        oneToucDialog = builder.neutralText("取消").onNeutral(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                // OneToucDialog.startQuickProgressTimer(finalOneToucDialog);
            }
        })
                .setType(OneToucDialog.Builder.ONE_TOUCH_TYPE_DOWNLOAD)
                .cancelable(false).setShowDownloadProgress(true).setmWidth(width)
                .setmHeight(height)
                .show();
        //OneToucDialog.startProgressTimer(oneToucDialog);
    }

    private String getMakeDocString() {
        return makeDocString = new GsonBuilder()
                .registerTypeAdapter(InchingCoreRootNoPPTV10Bean.class, new CoreObjToJsonNoPPTRules())
                .registerTypeAdapter(NoPPTRootTextValueV10Bean.class, new RootTextValueV10RemoveToJsonRules())
                .create().toJson(noPptCoreData);
    }

    @Override
    public void loadPreviewBgSuccess(String result) {
        dismissProgressDialog();
        if (getState().equals(UserMakeTag.CLOSE)) {
            //  showProgressDialogWithText("正在保存");
            dismissProgressDialog();
            finish();
        } else if (getState().equals(UserMakeTag.SAVE)) {
            dismissProgressDialog();
            // OneTouchProgressDialog.getInstance().builder(MakeActivity.this);
            T_.showCustomToast("存草稿成功");
        }
        currentDocString = new GsonBuilder()
                .registerTypeAdapter(InchingCoreRootNoPPTV10Bean.class, new CoreObjToJsonNoPPTRules())
                .registerTypeAdapter(NoPPTRootTextValueV10Bean.class, new RootTextValueV10RemoveToJsonRules())
                .create().toJson(noPptCoreData);
        VideoPreviewBean videoPreviewBean = new Gson().fromJson(result, VideoPreviewBean.class);
        Bundle bundle = new Bundle();
        bundle.putString(AppConst.DOCID, videoPreviewBean.getId() + "");
        if (getState().equals(UserMakeTag.MAKE)) {
            openActivity(V1_4_VideoPreviewActivity.class, bundle);
        } else if (getState().equals(UserMakeTag.SHOW)) {
            openActivity(VideoPlayPreviewActivity.class, bundle);
        }

        if (mPresenter == null) {
            return;
        }

//        if (mPresenter.makeProductContrl.oneToucDialog != null) {
//            if (mPresenter.makeProductContrl.oneToucDialog.isShowing()) {
//                mPresenter.makeProductContrl.oneToucDialog.dismiss();
//            }
//        }
//        if (mPresenter.makeProductContrl != null) {
//            mPresenter.makeProductContrl = null;
//        }

    }

    @Override
    public void loadPreviewFail(String result) {
        dismissProgressDialog();
    }

    //制作成功
    @Override
    public void makeSuccess(String result) {
        //制作成功  个人中心刷新作品
        //作品制作完成  通知我的页面刷新作品
        UpdateUserAction updateUserAction = new UpdateUserAction();
        updateUserAction.setSubType(TYPE_CREATEWORK);
        EventBus.getDefault().post(updateUserAction);
        //制作完成  保存的话直接退出  否则执行预览
        //TODO
        if (getState().equals(UserMakeTag.CLOSE)) {
            //  showProgressDialogWithText("正在保存");
            dismissProgressDialog();
            finish();
        } else if (getState().equals(UserMakeTag.SAVE)) {
            dismissProgressDialog();
            // OneTouchProgressDialog.getInstance().builder(MakeActivity.this);
            T_.showCustomToast("存草稿成功");
        } else {
            JSONObject jsonObject = JSON.parseObject(result);
            String docId = jsonObject.getString("docId");
            //L_.e(docId);
            mPresenter.loadDocPreview(docId);
        }
    }

    @Override
    public void setProductId(int productId) {
        if (noPptCoreData != null) {
            noPptCoreData.setProductId(productId);
            currentDocString = new GsonBuilder()
                    .registerTypeAdapter(InchingCoreRootNoPPTV10Bean.class, new CoreObjToJsonNoPPTRules())
                    .registerTypeAdapter(NoPPTRootTextValueV10Bean.class, new RootTextValueV10RemoveToJsonRules())
                    .create().toJson(noPptCoreData);

            makeDocString = currentDocString;
        }
    }

    @Override
    public void showLoadPreviewPorgress() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }

    /**
     * 从不同的界面返回 执行不同的操作
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (videoEditAdapter == null) {
            return;
        }

        //选择视频回调
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                    String videoUrl = null;
                    for (LocalMedia media : selectList) {
                        Log.i("图片-----》", media.getPath());
                        videoUrl = media.getPath();
                        L_.e("视频-----》", media.getPath());
                    }
                    String[] strings = UIUtils.videoWHDA(videoUrl);
                    String width = strings[0];//宽
                    String height = strings[1];//高
                    String angle = strings[2];
                    Intent intent = new Intent(MakeActivity.this, CutVideoActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString(AppConst.VIDEOURL, videoUrl);
                    bundle.putString(AppConst.VIDEOW, width);
                    bundle.putString(AppConst.VIDEOH, height);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 8000);
                    break;

            }
        }


        if (data != null) {
            if (requestCode == AppConst.TOPHOTO) {
                //图片裁剪
                if (videoEditAdapter.getNowImgRootValue().getPos().getServiceH() == -1) {
                    videoEditAdapter.getNowImgRootValue().getPos().setServiceH(videoEditAdapter.getNowImgRootValue().getPos().getH());
                }
                if (videoEditAdapter.getNowImgRootValue().getPos().getServiceW() == -1) {
                    videoEditAdapter.getNowImgRootValue().getPos().setServiceW(videoEditAdapter.getNowImgRootValue().getPos().getW());
                }
                int serviceWidth = (int) videoEditAdapter.getNowImgRootValue().getPos().getServiceW();
                int serviceHeight = (int) videoEditAdapter.getNowImgRootValue().getPos().getServiceH();
                Intent intent = CommonUtils.createToPhotoIntent(data, MakeActivity.this, serviceWidth, serviceHeight);
//                Intent intent = CommonUtils.createToPhotoIntent(data, MakeActivity.this);
//                int[] imagePicRelWH = CommonUtils.getImagePicRelWH(data, MakeActivity.this);
//                int w = imagePicRelWH[0];
//                int h = imagePicRelWH[1];
                if (intent == null) {
                    T_.showCustomToast("选择的文件不是图片", true);
                    return;
                }
//
//                //设置选择图片真实宽高
//                videoEditAdapter.getNowImgRootValue().getPos().setW(w);
//                videoEditAdapter.getNowImgRootValue().getPos().setH(h);
//
//                NoPPTRootImageValueV10Bean nowImgRootValue = videoEditAdapter.getNowImgRootValue();
//                CompoundPathsBean mask = nowImgRootValue.getMask();
//                //为了传入宽高
//                Gson gson = new Gson();
//                String maskJson = gson.toJson(mask);
                //向ClipAct传递mask
//                intent.putExtra(AppConst.TOPHOTO_MASK, maskJson);
                startActivityForResult(intent, AppConst.CHANGE_IMG_RESULT);
            } else if (requestCode == AppConst.CHANGE_IMG_RESULT) {
                String pathName = data.getStringExtra(AppConst.LOCAL_PHOTO_PATH_NAME);
                L_.i("CHANGE_IMG_RESULT===" + pathName);
                //设置选择图片真实宽高

                videoEditAdapter.getNowImgRootValue().getPos().setW(data.getIntExtra(AppConst.PHOTO_BITMAP_W, -1));
                videoEditAdapter.getNowImgRootValue().getPos().setH(data.getIntExtra(AppConst.PHOTO_BITMAP_H, -1));
                videoEditAdapter.getNowImgRootValue().setValue(pathName);
                ImageView nowClickImg = videoEditAdapter.getNowClickImg();
                Glide.with(MakeActivity.this).applyDefaultRequestOptions(new RequestOptions().placeholder(R.drawable.place_icon)
                        .error(R.drawable.place_icon)).load(pathName).thumbnail(0.1f).into(nowClickImg);

                videoEditAdapter.getNowImgMask().bringToFront();
                videoEditAdapter.videoNotifyItemChanged(false);

            } else if (requestCode == AppConst.REFRESH) {
                //String videoUrl = data.getStringExtra("videoUrl");
                // String imageUrl = data.getStringExtra("imageUrl");
                ClipVideoBean clipVideoBean = (ClipVideoBean) data.getSerializableExtra("videoBean");
                // T_.showCustomToast(clipVideoBean.toString());
                videoEditAdapter.getRootVideoValueV10Bean().setUrl(clipVideoBean.getVideoUrl());
                videoEditAdapter.getRootVideoValueV10Bean().setValue(clipVideoBean.getVideoThumb());
                videoEditAdapter.getRootVideoValueV10Bean().setDuration(Double.valueOf(clipVideoBean.getD()));
                PosBean pos = videoEditAdapter.getRootVideoValueV10Bean().getPos();
                pos.setH(Float.valueOf(clipVideoBean.getH()));
                pos.setW(Float.valueOf(clipVideoBean.getW()));
                pos.setAn(Integer.valueOf(clipVideoBean.getR()));
                L_.e("requestCode" + JSON.toJSONString(videoEditAdapter.getRootVideoValueV10Bean()));
                ImageView nowClickImg = videoEditAdapter.getNowClickImg();
                //.thumbnail(0.1f)
                Glide.with(MakeActivity.this).applyDefaultRequestOptions(new RequestOptions().placeholder(R.drawable.place_icon)
                        .error(R.drawable.place_icon)).load(clipVideoBean.getVideoThumb()).into(nowClickImg);
                videoEditAdapter.videoNotifyItemChanged(true);

            }
        }
    }

    //onCreate调用
    private void registerExitReceiver() {
        IntentFilter exitFilter = new IntentFilter();
        exitFilter.addAction(BroadcastAction.EXIT_THREE_LOGIC);
        registerReceiver(quitThreeLogicBroadcast, exitFilter);
    }

    //onDestory反注册
    private void unRegisterExitReceiver() {

        unregisterReceiver(quitThreeLogicBroadcast);
    }

    protected void sendRemoveThreeLogic() {
        Intent intent = new Intent();
        intent.setAction(BroadcastAction.EXIT_THREE_LOGIC);
        sendBroadcast(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegisterExitReceiver();
    }

    //滑动监听
    private class MyRecyclerViewScrollListener extends RecyclerView.OnScrollListener {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
            // 当不滚动时
            int firstPostion = manager.findFirstVisibleItemPosition();
            int lastPosition = manager.findLastVisibleItemPosition();
            //当前状态为停止滑动状态SCROLL_STATE_IDLE时
            if (newState == RecyclerView.SCROLL_STATE_IDLE) {

            }
        }

    }

    //滑动监听
    private class ViewPagerRecyclerViewScrollListener extends RecyclerView.OnScrollListener {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            CoverFlowLayoutManger manager = (CoverFlowLayoutManger) recyclerView.getLayoutManager();
            // 当不滚动时
            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                // L_.e(manager.getCenterPosition() + "");
                tvPageTag.setText((manager.getCenterPosition() + 1) + "/" + wantData.size());
                // idRvData.smoothScrollToPosition(manager.getCenterPosition());
            } else if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {

            }
        }
    }

    public class ViewPagerAdapter extends ABaseRefreshAdapter<String> {

        public ViewPagerAdapter(Context context, List<String> datas, int itemLayoutId) {
            super(context, datas, itemLayoutId);
        }

        @Override
        protected void convert(BaseRecyclerHolder var1, String var2, int position) {

            // RelativeLayout ry=var1.getView(R.id.id_ig_itme_ry);
            ImageView imageView = var1.getView(R.id.id_ig_vp);
            ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
            layoutParams.width = UIUtils.WHD()[0] / 4 + UIUtils.WHD()[0] / 2;
            layoutParams.height = (int) (layoutParams.width * 1.0f * 9.0f / 16.0f);


            //  viewpagerTopmargen = (UIUtils.dip2px(180) - layoutParams.height) / 2;
            L_.i("convert===" + layoutParams.width + "layoutParams.height===" + layoutParams.height);
            imageView.setLayoutParams(layoutParams);
            ImageLoader.getInstance().showImage(MakeActivity.this, var2, imageView);
        }
    }
}
